import React, {Component} from 'react'
import { FormattedMessage, injectIntl } from 'react-intl';
import {actions} from "mirrorx";
import {InputNumber, Select, FormControl, Table, Message} from "tinper-bee";
import Radio from 'bee-radio';
import moment from 'moment'
import DatePicker from "bee-datepicker";
import SearchPanel from 'components/SearchPanel';
import RefComponent from 'components/RefComponent';
import FormList from 'components/FormList'
import FormError from 'components/FormError';
import {deepClone,getValidateFieldsTrim,initValueString} from "utils";

import {searchField} from '../InitTemplate';
import zhCN from "rc-calendar/lib/locale/zh_CN";

let {RangePicker} = DatePicker;

import './index.less'

const FormItem = FormList.Item;
const {Option} = Select;
const format = "YYYY";
const {YearPicker} = DatePicker;

class SearchAreaForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refStateParam:{}
        }

    }
    /** 查询数据
     * @param {*} error 校验是否成功
     * @param {*} values 表单数据
     */
    search = () => {
        this.props.form.validateFields((err, _values) => {
            let values = getValidateFieldsTrim(_values);
           
            for(let attr in values){
                if(values[attr]===null || values[attr]==="" || (values[attr]&&values[attr].length == 0))
                    delete values[attr];
            }

            this.getQuery(values, 0);
        });

    }


    /**
     * 重置 如果无法清空，请手动清空
     */
    reset = () => {
        let param = {};
        let _this = this;
        searchField.map(item => {
            param[item.enname] = ""
            _this.props.form.setFieldsValue(param);
        })
    }


    /** 查询数据
     * @param {Object} values 表单对象
     * @param {Number} type 1位清空操作，0位查询操作
     */
    getQuery = (values, type) => {
        let queryParam = deepClone(this.props.queryParam);
        queryParam.pageParams.pageIndex = 0;
        queryParam.pageParams.pageSize = 10;
        queryParam.whereParams = values;
        actions.ActivityPlanTemplate.updateState(queryParam);
        if (type === 0) {
            actions.ActivityPlanTemplate.loadList(queryParam);
        }
    }

    //拼接下级级联的上级参数值
    calcuParm = (item,data,fieldName,childType) => {
        let {refStateParam} = this.state;
        let tempParam = {};
        let cascadeName = item.cascadeName;
        // let param = item.param;
        // if(!param)  param={};
        if(!cascadeName) return param;
        //待优化 先取一个级联参数
        let paramName = cascadeName[0];
        
        tempParam[paramName] = data[0] && data[0].refpk || null;
        //param 配置数据里的固定参数
        //tempParam 依赖字段计算出来的参数
        //tempParam = Object.assign({}, param, tempParam);
        let _thisParmField = `${fieldName}_${childType}`;
        refStateParam[_thisParmField] = tempParam;
        this.setState({refStateParam});
    }
    //重置下级级联参照
    resetOfferRef = (item,childType,childRowData) => {
        if(!item.offers) return;
        let param = {}
        param[item.offers] = null;
        //重置级联下级参照值
        this.props.form.setFieldsValue(param);
    }

    renderFunc = (flag) => {
        let {queryParam,selectDataList={}} = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        let dom = [];
        let childRowData = queryParam.whereParams;
        let self = this;
        let childType = "DataHeader";
        let required;
        searchField.forEach((item,index) => {
            required = item.required;
            if(flag == 1 && index>2) {
                return false;
            }
            if(flag == 2 && index<3) {
                return true;
            }
            switch(item.type) {
                case 'FormControl':
                        dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                required={item.required}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                label={item.zhname}
                            >
                                <FormControl 
                                    key={`${item.enname}${index}`}
                                    disabled={!item.edit}
                                    {...getFieldProps(`${item.enname}`,{
                                        initialValue: childRowData[item.enname] || "",
                                        rules: [{
                                            required: required, message: "请输入",
                                        }],
                                    })}
                                />
                        </FormItem>);
                        break;
                case 'InputNumber':
                    dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <InputNumber toThousands={true}  
                                    key={`${item.enname}${index}`}
                                    iconStyle="one" step={1} disabled={!item.edit}
                                    {...getFieldProps(`${item.enname}`, {
                                        initialValue: (typeof childRowData[item.enname]) === "number" ? childRowData[item.enname] : 0,
                                        rules: [{
                                            required: required, message: "请输入",
                                        }],
                                    })}
                                />
                    </FormItem>);
                            break;
                case 'DatePicker':
                        dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <DatePicker 
                                    key={`${item.enname}${index}`}
                                    format={item.format || format} disabled={!item.edit}
                                    {...getFieldProps(`${item.enname}`, {
                                        initialValue: childRowData[item.enname] && moment(childRowData[item.enname]) || moment(),
                                        validateTrigger: 'onBlur',
                                        rules: [{ 
                                            required: required, 
                                            message: '请选择',
                                         }],
                                    })}
                                />
                        </FormItem>);
                            break;
                case 'RangePicker':
                        dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <RangePicker 
                                    key={`${item.enname}${index}`}
                                    disabled={!item.edit}
                                    {...getFieldProps(`${item.enname}`, {
                                        initialValue:childRowData[item.enname] || [],
                                        validateTrigger: 'onBlur',
                                        rules: [{ required: required, message: '请选择', }],
                                    })}
                                />
                        </FormItem>);
                            break;
                case 'RefComponent':
                        dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <RefComponent
                                    key={`${item.enname}${index}`}
                                    constparam = {item.param}
                                    multiple={item.multiple || false}
                                    aliasparam = {self.state.refStateParam}
                                    aliasfieldName={item.alias}
                                    title={item.zhname}
                                    refName={item.refname}
                                    childType = {childType}
                                    fieldName={item.enname}
                                    clearMatchData={this.clearMatch}
                                    rules={[
                                        { 
                                            required: required, 
                                            message: '请选择',
                                            pattern: item.required && /[^{"refname":"","refpk":"","refcode":""}|{"refpk":"","refname":"","refcode":""}]/
                                        }
                                    ]}
                                    initialValue={childRowData[item.enname] || initValueString(childRowData[item.showname],childRowData[item.enname],item.required)}
                                    refTableOnClickSave={(refName, fieldName, data) => {
                                        if(item.offers) {
                                            self.resetOfferRef(item,childType,childRowData);
                                        }
                                        if(item.cascadeName) {
                                            //item 配置数据
                                            //data 参照返回数据
                                            //fieldName 参照Id字段
                                            //childType 字表所属字段
                                            self.calcuParm(item,data,fieldName,childType);
                                        }
                                    }}
                                    form={self.props.form}
                                />
                        </FormItem>);
                            break;
                case 'Select':
                        let options = selectDataList[item.code] || item.options;
                        dom.push(<FormItem
                                className="time"
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <Select
                                    key={`${item.enname}${index}`}
                                    disabled={!item.edit}
                                    {
                                    ...getFieldProps(`${item.enname}`, {
                                        initialValue: childRowData[item.enname] || "",
                                        rules: [{ 
                                            required: required, 
                                            message: '请选择',
                                         }],
                                    })
                                    }
                                >
                                    <Option value="">请选择</Option>
                                    {
                                        options && options.map((item, index) => {
                                            return (
                                                <Option key={index} value={item.code}>{item.name}</Option>
                                            )
                                        })
                                    }
                                    
                                </Select>
                        </FormItem>);
                            break;
                    case 'Radio':
                            dom.push(<FormItem
                                    key={item.enname}
                                    required={item.required}
                                    FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                    label={item.zhname}
                                >
                                    <Radio.RadioGroup
                                    key={`${item.enname}${index}`}
                                    disabled={!item.edit}
                                        {
                                        ...getFieldProps(`${item.enname}`, {
                                            initialValue: childRowData[item.enname] || '1',
                                            rules: [{ 
                                                required: required, 
                                                message: '请选择',
                                             }],
                                        }
                                        ) }
                                    >
                                         {
                                            item.options && item.options.map((itemoption, index) => {
                                                return (
                                                    <Radio 
                                                    disabled={!item.edit}
                                                    key={index} value={itemoption.key}>{itemoption.value}</Radio>
                                                )
                                            })
                                        }
                                    </Radio.RadioGroup>
                            </FormItem>);
                                break;
                    default: break;
            }
        })
        return dom;
    }


    render() {
        let {form,onCallback} = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        let self = this;
        let headchildren = <FormList size="sm">
                                {self.renderFunc(1)}

                            </FormList> 
        return (
            <SearchPanel
                form={form}
                reset={this.reset}
                onCallback={onCallback}
                intl={this.props.intl}
                search={this.search}
                headchildren={headchildren}>
                <FormList size="sm">
                {self.renderFunc(2)}
                </FormList> 
            </SearchPanel>
        )
    }
}

export default FormList.createForm()(injectIntl(SearchAreaForm))
